package cn.netswap.jeegorilla.framework.security.web;

import cn.netswap.jeegorilla.framework.security.consts.SecurityConstants;
import cn.netswap.jeegorilla.framework.security.model.SysUser;
import cn.netswap.jeegorilla.framework.security.social.SocialUserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.web.ProviderSignInUtils;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by lai_gw on 2020/3/22.
 */
@Controller
@RequestMapping("gorillaSocial")
public class GorillaSocialController {

    Logger log = LoggerFactory.getLogger(GorillaSocialController.class);

    @Autowired
    private ProviderSignInUtils providerSignInUtils;

    /**
     * 获取当前用户的社交信息
     * @param request
     * @return
     */
    @GetMapping("/social/userinfo")
    @ResponseBody
    public SocialUserInfo getSocialUserInfo(HttpServletRequest request) {
        SocialUserInfo userInfo = new SocialUserInfo();
        Connection<?> connection = providerSignInUtils.getConnectionFromSession(new ServletWebRequest(request));
//        userInfo.setProviderId(connection.getKey().getProviderId());
        userInfo.setNickname(connection.getDisplayName());
        userInfo.setHeadimg(connection.getImageUrl());
        return userInfo;
    }

    @RequestMapping("/social/binding")
    public String binding(HttpServletRequest request) {
        String userId =  request.getParameter("username");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //这里面要实现根据用户密码查询用户是否存在如果存在才绑定（也可以通过发邮件事实现）
        providerSignInUtils.doPostSignUp(userId, new ServletWebRequest(request));
        return "redirect:"+ SecurityConstants.DEFAULT_LOGIN_PAGE;
    }

    @GetMapping("/user/me")
    @ResponseBody
    public String me() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        return auth.toString();
    }


}
